package Offer.offer;

/**
 * 数值的整数次方
 * @author leiwenkang
 * @date 2020/4/6
 */
public class Test11数值的整数次方 {
    public static void main(String[] args) {
        System.out.println(power(4, 3));
    }

    public static double power(double base, int exponent) {
        //0的正整数次方为0 ，0的负整数次方，为异常数据
        if (isEqual(base, 0.0)) {
            if (exponent >= 0) {
                return 0;
            } else {
                throw new RuntimeException("算术错误");
            }
        }

        int absExponent = exponent;
        if (exponent < 0) {
            absExponent = -exponent;
        }

        double result = 1.0;
        for (int i = 0; i < absExponent; i++) {
            result *= base;
        }

        if (exponent < 0) {
            result = 1.0 / result;
        }
        return result;
    }

    private static boolean isEqual(double num1, double num2) {
        return num1 - num2 < 0.0000000001 && num1 - num2 > - 0.0000000001;
    }
}
